<style lang="less">
@import "../../styles/common.less";
.blue-tag{
    margin:2px 4px;
    display: inline-block;
    padding:2px 6px;
    color:#fff;
    background:#2d8cf0;
}
.is_invalid_row .ivu-table-column-center{
  background-color: #ff6600;
  color: #fff;
}
</style>

<template>
  <div class="margin-top-10">
    <Form :label-width="80" size="small" inline>
      <!-- <FormItem label="集团">
        <Input
          v-model.trim="queryForm.group_name"
          @on-enter="searchClassAttendance"
          placeholder="请输入集团名称" 
          style="width: 120px;margin-right:3px"
        ></Input>
      </FormItem> -->
      <FormItem label="校区ID">
        <Input
          v-model.trim="queryForm.campus_id"
          @on-enter="searchClassAttendance"
          clearable
          placeholder="请输入校区ID" 
          style="width: 120px;margin-right:3px"
        ></Input>
      </FormItem>
      <FormItem label="班级ID">
        <Input
          v-model.trim="queryForm.class_id"
          @on-enter="searchClassAttendance"
          placeholder="请输入班级ID" 
          clearable
          style="width: 120px;margin-right:3px"
        ></Input>
      </FormItem>
      <FormItem label="教室ID">
        <Input
          v-model.trim="queryForm.classroom_id"
          @on-enter="searchClassAttendance"
          placeholder="请输入教室ID" 
          clearable
          style="width: 150px;margin-right:3px"
        ></Input>
      </FormItem>
      <!-- <FormItem label="项目">
        <Input
          v-model.trim="queryForm.class_type"
          @on-enter="searchClassAttendance"
          placeholder="请输入项目名称" 
          style="width: 150px;margin-right:3px"
        ></Input>
      </FormItem> -->
      <!-- <FormItem label="课次">
        <Input
          v-model.trim="queryForm.class_time_name"
          @on-enter="searchClassAttendance"
          placeholder="请输入课次名称" 
          style="width: 150px;margin-right:3px"
        ></Input>
      </FormItem> -->
      <FormItem label="上课日期" :label-width="60">
          <!-- <DatePicker v-model="queryForm.class_date" type="date" placeholder="请选择上课日期" style="width: 168px"></DatePicker> -->
          <DatePicker v-model="dateRange" type="daterange" placement="bottom-end" placeholder="请选择上课日期" style="width: 180px"></DatePicker>
      </FormItem>
      <!-- <FormItem :label-width="60" label="上课时间">
        <TimePicker v-model="class_time_range" confirm format="HH:mm" type="timerange" placement="bottom-end" placeholder="请选择时间段" style="width: 120px"></TimePicker>
      </FormItem> -->
      <FormItem>
        <Button @click="searchClassAttendance" type="primary">查询</Button>
        <Button @click="handleBatchExport">批量导出</Button>
      </FormItem>
    </Form>
    <div class="margin-top-10">
      <Table @on-selection-change="selectionChange" :columns="classAttendanceColumn" :data="classAttendanceData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalClassAttendance"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getClassAttendance"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalClassAttendance}}条</Page>
    </Row>

    <Modal
      v-model="addClassAttendanceModal"
      v-bind:title="modalTitle"
      :scrollable="true"
      class-name="vertical-center-modal"
      :mask-closable="false"
      @on-cancel="resetForm('classAttendanceInfoForm')"
     >
      <Form
        ref="classAttendanceInfoForm"
        :label-width="80"
        :model="classAttendanceInfo"
        :rules="classAttendanceInfoRules"
      >
        <FormItem label="主讲老师" prop="class_teacher">
            <Input v-model.trim="classAttendanceInfo.class_teacher" :maxlength="20" placeholder="请填写主讲老师姓名" />
        </FormItem>
        <FormItem label="上课时间" prop="class_time_range">
          <TimePicker v-model="classAttendanceInfo.class_time_range" confirm format="HH:mm" type="timerange" placement="bottom-end" placeholder="请选择时间段" style="width: 168px"></TimePicker>   
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="handleSubmitClassAttendance('classAttendanceInfoForm')">提交</Button>
      </div>
    </Modal>

    <!-- 查看学生考勤 -->
    <Modal
        v-model="studentAttendanceModal"
        width="660px"
        title="学生考勤">
        <div style="display:flex;justify-content:space-between;margin-bottom:10px;">
          <div>
            考勤日期：{{studentAttendanceDate}} 
            <span style="margin-left:20px">上课时间：{{attendanceClassStartTime}}-{{attendanceClassEndTime}}</span>
          </div>
          <Button type="primary" @click="handleExportClassAttendance(currentAttendanceItem)">导出</Button>
        </div>
        <Table :row-class-name="rowClassName" :columns="studentAttendanceColumn" :data="studentAttendanceTableData"></Table>
        <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import {
  getClassAttendance,
  updateClassAttendance,
  deleteClassAttendance,
  exportClassAttendance
} from "../../controllers/classAttendance";
import HorizonUploader from "./components/HorizonUploader.vue";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";
import _ from "lodash";
import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";
import moment from "moment";

const validatorTimeRange = (rule,value,cb) => {
  if(value&&value[0]&&value[1]){
    return cb()
  }
  cb(new Error('请选择上课时间'))
}
export default {
  name:'classAttendance',
  components: {
    HorizonUploader,
    Tooltip,
    Btn
  },
  data() {
    return {
      addClassAttendanceModal: false,
      tableLoading: true,
      queryForm:{
        group_name:'',
        campus_name:'',
        campus_id:'',
        class_name:'',
        class_id:'',
        classroom_name:'',
        classroom_id:'',
        class_type:'',
        class_time_name:'',
        // class_date:'',
        class_date_from:'',
        class_date_to:'',
        class_start_time:'',
        class_end_time:'',
      },
      dateRange:'',
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalClassAttendance: 0,
      class_time_range:'',
      selectionRows:[],//批量选择
      classAttendanceColumn: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed:'left'
        },
        {
          title: "集团名称",
          align: "center",
          key: "group_name",
          width: 160
        },
        {
          title: "校区ID",
          align: "center",
          key: "campus_id",
          width: 160
        },
        {
          title: "教室ID",
          align: "center",
          key: "classroom_id",
          width: 160
        },
        {
          title: "课次ID",
          key: "lesson_id",
          align: "center",
          width: 160
        },
        // {
        //   title: "班级名称",
        //   align: "center",
        //   key: "class_name",
        //   width: 160
        // },
        // {
        //   title: "班级编号",
        //   key: "class_num",
        //   align: "center",
        //   width: 200
        // },
        {
          title: "上课日期",
          align: "center",
          width: 160,
          render: (h, {row})=>{
            const dayObj = {
              0:'周天',
              1:'周一',
              2:'周二',
              3:'周三',
              4:'周四',
              5:'周五',
              6:'周六',
            }
            return (
              <div>
                <span style="margin-right:6px">{dayObj[new Date(row.attendance_start_date).getDay()]}</span>
                {moment(row.attendance_start_date).format('YYYY-MM-DD')}
              </div>
            )
          }
        },
        {
          title: "上课时间",
          align: "center",
          width: 160,
          render: (h, {row})=>{
            return (
              <div>
                {moment(row.class_start_time).format('YYYY-MM-DD HH:mm:ss')}
                -
                {moment(row.class_end_time).format('YYYY-MM-DD HH:mm:ss')}
              </div>
            )
          }
        },
        // {
        //   title: "项目",
        //   align: "center",
        //   key: "class_type",
        //   width: 160,
        // },
        // {
        //   title: "主讲老师",
        //   align: "center",
        //   key: "class_teacher",
        //   width: 160,
        // },
        {
          title: "教室设备",
          align: "center",
          minWidth: 300,
          render: (h, {row, column, index}) => {
              const devices = row.device_collection;
              return (
                  <div>
                    {
                        devices.map(item=>{
                            return (
                                <span class="blue-tag">{item.device_id}</span>
                            )
                        })
                    }
                  </div>
              )
          }
        },
        {
          title:'学生考勤',
          align:'center',
          width:100,
          fixed:'right',
          render: (h,{row})=>{
            return (
              <i-button type="primary" size="small" onClick={()=>{this.previewStudentAttendance(row)}}>详情</i-button>
            )
          }
        },
        {
          title: "操作",
          align: "center",
          width: 160,
          fixed:'right',
          render: (h, { row }) => {
            const _id = row._id;
            return (
              <div class="operate-column">
                  {
                    /*
                      <Btn
                        type="text"
                        onClick={() => this.handleEditClassAttendance(row)}
                      >编辑</Btn>
                    */
                  }
                  <Btn
                    type="text"
                    onClick={() => this.handleExportClassAttendance(row)}
                  >导出</Btn>
                {
                  /*
                    <Tooltip content="删除" placement="bottom">
                      <Btn
                        style={{ background: `url( ${iconDelete})` }}
                        onClick={() => this.handleDelClassAttendance(_id, row.class_type)}
                      />
                    </Tooltip>
                  */
                }
                
              </div>
            );
          }
        }
      ],
      classAttendanceData: [],
      ipcList:[],
      classAttendanceInfo: {
        _id:'',
        class_teacher:'',
        class_time_range:'',
        class_start_time:'',
        class_end_time:''
      },
      modalTitle: "",
      classAttendanceInfoRules: {
          class_teacher: [
            { required: true, message: "请输入主讲老师姓名", trigger: "blur" }
          ],
          class_time_range: [
              {required: true, validator: validatorTimeRange, message: "请选择上课时间", trigger: "blur"}
          ],
      },
      uploadModal: false,

      // 考勤信息
      currentAttendanceItem:{},
      studentAttendanceModal:false,
      studentAttendanceDate:'',//考勤日期
      attendanceClassStartTime:'',
      attendanceClassEndTime:'',
      studentAttendanceTableData:[],
      studentAttendanceColumn:[
        {
          title:'学生姓名',
          key:'student_name',
          align:'center',
          width:120,
        },
        {
          title:'学号',
          key:'student_num',
          align:'center',
          width:120,
        },
        {
          title:'最早打卡时间',
          key:'attendance_start_time',
          align:'center',
          width:120,
          render: (h,{row})=>{
            return (
              <span>{row.attendance_start_time?moment(row.attendance_start_time).format('HH:mm'):'-'}</span>
            )
          }
        },
        {
          title:'最晚打卡时间',
          key:'attendance_end_time',
          align:'center',
          width:120,
          render: (h,{row})=>{
            return (
              <span>{row.attendance_end_time?moment(row.attendance_end_time).format('HH:mm'):'-'}</span>
            )
          }
        },
        {
          title:'标识',
          align:'center',
          minWidth:100,
          render: (h,{row})=>{
            let currentTime = +new Date(),remark="-";
            let classStartTime = new Date(this.studentAttendanceDate).setHours(this.attendanceClassStartTime.slice(0,2),this.attendanceClassStartTime.slice(-2),0,0);
            let classEndTime = new Date(this.studentAttendanceDate).setHours(this.attendanceClassEndTime.slice(0,2),this.attendanceClassEndTime.slice(-2),0,0);
            if(row.is_invalid>=10){
              remark = '蹭课'
            }else if(currentTime<classEndTime){
              remark = '-'
            }else if(!row.attendance_start_time){
              remark = '旷课'
            } else if(classStartTime<row.attendance_start_time){
              remark = '迟到'
            } else if(classEndTime>row.attendance_end_time){
              remark = '早退'
            } else {
              remark = '正常'
            }
            return (
              <span>{remark}</span>
            )
          }
        }
      ]
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    },
  },
  //待考虑：初次加载表格的时机
  created() {
    // this.queryForm.class_date = new Date(new Date().setHours(0,0,0,0))
    this.dateRange = [new Date(new Date().setHours(0,0,0,0)),new Date(new Date().setHours(0,0,0,0))]
    this.queryForm.class_date_from = +this.dateRange[0]
    this.queryForm.class_date_to = +this.dateRange[1]+1000*60*60*24-1
    this.loadclassAttendanceData();
  },
  methods: {
    formatDay(days){
      const dayObj = {
        0:'周天',
        1:'周一',
        2:'周二',
        3:'周三',
        4:'周四',
        5:'周五',
        6:'周六',
      }
      if(!days||days.length===0){
        return ''
      }
      const strAry = []
      for(let key of days){
        strAry.push(dayObj[key])
      }
      return strAry.join(';')
    },
    getClassAttendance(page) {
      this.currentPage = page;
      this.tableLoading = true;
      this.loadclassAttendanceData();
    },
    // 查看学生考勤
    previewStudentAttendance(row){
      this.studentAttendanceModal = true
      this.studentAttendanceDate = moment(row.attendance_start_date).format('YYYY-MM-DD')
      this.attendanceClassStartTime = moment(row.class_start_time).format('YYYY-MM-DD HH:mm')
      this.attendanceClassEndTime = moment(row.class_end_time).format('YYYY-MM-DD HH:mm')
      this.studentAttendanceTableData = (row.student_collection||[]).filter(item=>!item.is_invalid||item.is_invalid>=10)
      this.currentAttendanceItem = row 
    },
    rowClassName(row,index){
      // 蹭课标示
      if(row.is_invalid){
        return 'is_invalid_row'
      }
      return ''
    },
    handleSubmitClassAttendance(form) {
      const submitInfo = Object.assign({},this.classAttendanceInfo)
      this.$refs[form].validate(valid => {
        if (valid) {
          if(submitInfo.class_time_range&&submitInfo.class_time_range[0]&&submitInfo.class_time_range[1]){
            submitInfo.class_start_time = submitInfo.class_time_range[0].replace(':','')
            submitInfo.class_end_time = submitInfo.class_time_range[1].replace(':','')
          }
          if(submitInfo._id){
            updateClassAttendance(
                submitInfo
            ).then(res => {
                if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClassAttendanceModal = false;
                this.resetForm(form);
                this.getClassAttendance(this.currentPage);
                }
            });
          }else{
            addClassAttendance(
              submitInfo
            ).then(res => {
              if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClassAttendanceModal = false;
                this.resetForm(form);
                this.getClassAttendance(this.currentPage);
              }
            });
          }
        } else {
          this.$Message.error("填写项目验证失败!");
        }
      });
    },
    handleDelClassAttendance(id, name) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除考勤表【" + name + "】？",
        onOk: () => {
          // 删除基本信息
          deleteClassAttendance({ _id: [id] }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.getClassAttendance(this.currentPage);
            }
          });
        }
      });
    },
    handleEditClassAttendance(row) {
      const data = row || {};
      this.modalTitle = "修改课程信息";
      this.classAttendanceInfo._id = row._id;
      this.classAttendanceInfo.class_teacher = data.class_teacher;
      this.classAttendanceInfo.class_time_range = [data.class_start_time,data.class_end_time];
      this.addClassAttendanceModal = true;
    },
    handleExportClassAttendance(row){
      if(!row) return
      const name = `${moment(row.attendance_start_date).format('YYYY-MM-DD')}-${row.class_name}-考勤表`
      this.exportAttendance([row._id],name)
    },
    selectionChange(selection){
      this.selectionRows = selection
    },
    handleBatchExport(type){
      if(this.selectionRows.length<=0){
        return this.$Message.error('请选择考勤信息')
      }
      const ids = this.selectionRows.map(item=>item._id)
      this.exportAttendance(ids)
    },
    exportAttendance(ids,name='考勤表'){
      exportClassAttendance({
        ids
      }).then(res=>{
        if(res.type!=='application/octet-stream'){
          return this.$Message.error('导出失败')
        }
        const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
        const url = URL.createObjectURL(blob);
        const aLink = document.createElement('a');
        aLink.setAttribute('download',`${name}.xlsx`);
        aLink.setAttribute('href',url);
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink)
        URL.revokeObjectURL(blob);
      }).catch(err=>{
        console.log(err)
        this.$Message.error('导出失败')
      })
    },
    searchClassAttendance() {
      if(this.class_time_range&&this.class_time_range[0]&&this.class_time_range[1]){
        this.queryForm.class_start_time = this.class_time_range[0].replace(':','')
        this.queryForm.class_end_time = this.class_time_range[1].replace(':','')
      }else{
        this.queryForm.class_start_time = ''
        this.queryForm.class_end_time = ''
      }
      if(this.dateRange&&this.dateRange[0]&&this.dateRange[1]){
        this.queryForm.class_date_from = +this.dateRange[0]
        this.queryForm.class_date_to = +this.dateRange[1]+1000*60*60*24-1
      }else{
        this.queryForm.class_date_from = ''
        this.queryForm.class_date_to = ''
      }
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadclassAttendanceData();
    },
    loadclassAttendanceData() {
      getClassAttendance({
          page_num:this.currentPage, 
          page_size:this.pageSize, 
          ...this.queryForm,
          // class_date:this.queryForm.class_date&&this.queryForm.class_date.getTime()||''
        })
        .then(json => {
          let { total, data } = transclassAttendanceData(json);
          this.totalClassAttendance = total;
          this.classAttendanceData = data;
          this.tableLoading = false;
          let tmp = _.map(data, item => item.uid);
          return tmp;
        })
        // .then(uids => this.asyncAvatar(uids));
    },
    resetForm(form) {
      //解决对话框消失的时候字体变化问题
      setTimeout(() => {
        this.$refs[form].resetFields();
        this.classAttendanceInfo._id = null;
      }, 500);
    },
    handleUpload() {
      if (!this.$refs["uploader"].hasFile) {
        this.$Message.error("请先选择文件");
        return;
      }
      var formData = new FormData();
      formData.append("file", this.$refs["uploader"].file);
      uploadclassAttendanceData(formData).then(json => {
        if (json.code == 0) {
          this.$Message.success(json.msg);
          this.hideUploadModal();
          this.getClassAttendance(this.currentPage);
        }
      });
    },
    hideUploadModal() {
      this.$refs["uploader"].reset();
      this.uploadModal = false;
    },
  }
};

function transclassAttendanceData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {} };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }

  let { total, result } = data;

  return {
    total,
    data: result
  };
}

</script>